package com.jokey.vue.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jokey.vue.dto.HrRoleUpdateReq;
import com.jokey.vue.dto.PasswordUpdateReq;
import com.jokey.vue.mapper.HrMapper;
import com.jokey.vue.model.Hr;
import com.jokey.vue.model.HrRole;
import com.jokey.vue.service.HrRoleService;
import com.jokey.vue.service.HrService;
import com.jokey.vue.utils.HrUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author: JokeyZheng
 * @email: zhengjingfeng@ruqimobility.com
 * @created: 2021/11/26 15:14
 * @version: v1.0.0
 */
@Service
public class HrServiceImpl extends ServiceImpl<HrMapper, Hr>
        implements HrService {

    @Resource
    private HrRoleService hrRoleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<Hr> wrapper = new QueryWrapper<Hr>().eq("username", username);
        Hr hr = super.baseMapper.selectOne(wrapper);
        if (Objects.isNull(hr)) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        //查询角色
        hr.setRoles(baseMapper.getHrRolesById(hr.getId()));
        return hr;
    }

    @Override
    public boolean updateHrPassword(PasswordUpdateReq password) {
        Hr hr = baseMapper.selectById(password.getHrId());
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (encoder.matches(password.getOldPassword(), hr.getPassword())) {
            String encodePass = encoder.encode(password.getNewPassword());
            hr.setPassword(encodePass);
            return baseMapper.updateById(hr) != 0;
        }
        return false;
    }

    @Override
    public List<Hr> getAllHrs(String keywords) {
        Integer hrId = HrUtils.getCurrentHr().getId();
        return baseMapper.getAllHrs(hrId, keywords);
    }

    @Override
    public boolean updateHrRole(HrRoleUpdateReq req) {
        hrRoleService.remove(new QueryWrapper<HrRole>().eq("hr_id", req.getHrId()));
        List<HrRole> list = new ArrayList<>();
        for (Integer roleId : req.getRoleIds()) {
            HrRole hrRole = new HrRole();
            hrRole.setHrId(req.getHrId());
            hrRole.setRId(roleId);
            list.add(hrRole);
        }

        return hrRoleService.saveBatch(list);
    }
}
